import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:untitled2/utils/ApkUtils.dart';

class UpDataApp extends StatefulWidget {
  const UpDataApp({super.key});

  @override
  State<StatefulWidget> createState() {
    return _UpDataAppState();
  }
}

class _UpDataAppState extends State<UpDataApp> {
  var versionName = "";
  var apkUrl = "https://dl.hdslb.com/mobile/latest/android64/iBiliPlayer-bili.apk";
  var _downloadsDirectory = "";
  var saveApkPath = "";
  @override
  void initState() {
    super.initState();
    ApkUtils.instance.requestExternalStorageDirectory().then((onValue) {
      _downloadsDirectory = onValue;
      saveApkPath="$_downloadsDirectory/${ApkUtils.instance.getPathFileName(apkUrl)}";
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("更新APP"),
      ),
      body: Container(
        width: double.infinity,
        //横向排列
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center, // 垂直方向居中
            crossAxisAlignment: CrossAxisAlignment.center, // 水平
            children: [
              Text(
                "当前版本：$versionName",
                style: const TextStyle(fontSize: 20),
              ),
              const SizedBox(
                height: 20,
              ),
              Text(
                "下载目录---：${_downloadsDirectory}",
                style: const TextStyle(fontSize: 20),
              ),
              ElevatedButton(
                  onPressed: () async {
                    // 判断文件是否存在
                    bool fileExists = await File(saveApkPath).exists();
                    //判断文件是否存在
                    if (fileExists) {
                      ApkUtils.instance.installApk(saveApkPath);
                    } else {
                      ApkUtils.instance.downloadTaskId(apkUrl, _downloadsDirectory);
                    }
                    Fluttertoast.showToast(
                      msg: saveApkPath,
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.CENTER,
                      timeInSecForIosWeb: 1,
                      backgroundColor: Colors.black,
                      textColor: Colors.white,
                      fontSize: 16.0,
                    );
                  },
                  child: const Text("更新"))
            ]),
      ),
    );
  }
}
